package block;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

class SocketServer {

    class HandleThread extends Thread{
        private Socket socket ;
        public HandleThread(Socket socket){
            this.socket = socket;
        }

        @Override
        public void run() {

            try {
                InputStream inputStream = socket.getInputStream();
                byte[] bytes = new byte[1024];
                int len = 0;
                StringBuffer sb = new StringBuffer();
                while ((len = inputStream.read(bytes)) != -1){
                    sb.append(new String(bytes, 0, len, "utf-8"));
                }

                System.out.println("get message from client: " + sb);
                inputStream.close();
                socket.close();

            }catch (IOException  e){
                e.printStackTrace();
                try {
                    socket.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }

            }

        }
    }

    public void startServer() throws IOException{
        int port = 50000;
        ServerSocket server = new ServerSocket(port);

        System.out.println("server将一直等待连接的到来");
        while (true){
            final Socket socket = server.accept();

            System.out.println("Accepted connection from " + socket);
            new HandleThread(socket).start();

        }
    }


    public static void main(String[] args) throws IOException {

        SocketServer ss = new SocketServer();
        ss.startServer();

    }



}
